package com.by_man.presenter.module_health_management.health_reminder;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TimePicker;

import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.module_gestureLock.GestureLockActivity;

import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.Set;

/**
 * 设定闹钟服务
 * Created by man on 2017-02-21.
 */
public class HealthAlarmActivity extends AppCompatActivity {
    // 创建多选对话框的各项主题
    private String[] items = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
    // 记录多选对话框选择情况
    private boolean[] checkeditems = {false, false, false, false, false, false, false};
    // 标记是否全选了
    private boolean isAllChecked = false;
    // 多选对话框对象引用
    private AlertDialog mutiDialog;

    private Calendar calendar = Calendar.getInstance();

    // 记录任务数目，同时也作为任务id,初始设定为1.
    private int taskCount = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_alarm);
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, HealthReminderActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, HealthReminderActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode,event);
    }

    protected void onRestart()
    {
        super.onRestart();
        Intent intent=new Intent(this,GestureLockActivity.class);
        intent.putExtra("class",this.getClass().getName());
        intent.putExtra("position", 0);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        // 注册监听，进行相关设定
        // timePicker
        final TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);

        // EditTextShock
        final EditText editTextShock = (EditText) findViewById(R.id.editTextShock);
        final CheckBox checkBoxShock = (CheckBox) findViewById(R.id.checkBoxShock);

        // 设定弹出菜单项
        final PopupWindow popupWindow = new PopupWindow(this);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        View view = getLayoutInflater().inflate(R.layout.health_alarm_popup_menu, null);
        popupWindow.setContentView(view);

        LinearLayout parentLL = (LinearLayout) view.findViewById(R.id.parent);
        Button shockBtn = (Button) view.findViewById(R.id.shock_btn);
        Button ringBtn = (Button) view.findViewById(R.id.ring_btn);

        // 点击弹出菜单之外的范围，隐藏菜单
        parentLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        // 点击震动按钮，设定震动,弹出菜单隐藏
        shockBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editTextShock.setText("震动");
                popupWindow.dismiss();
            }
        });
        checkBoxShock.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isChecked())
                    popupWindow.showAsDropDown(HealthAlarmActivity.this.findViewById(R.id.health_alarm_root_view));
            }
        });
        // 点击铃声按钮，设定震动，弹出菜单隐藏
        ringBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editTextShock.setText("震动");
                popupWindow.dismiss();
            }
        });

        // 为editTextShock设定监听
        editTextShock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.showAsDropDown(HealthAlarmActivity.this.findViewById(R.id.health_alarm_root_view));
            }
        });

        // EditTextItem
        final EditText editTextItem = (EditText) findViewById(R.id.editTextItem);
        ImageButton imageButton = (ImageButton) findViewById(R.id.image_btn);
        // 创建弹出菜单
        final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
        final String items[] = new String[]{"闹钟1", "闹钟2", "闹钟3", "闹钟4"};
        listPopupWindow.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
        listPopupWindow.setAnchorView(editTextItem);            // 关联锚点，即确定弹出窗口显示位置
        listPopupWindow.setModal(true);
        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                editTextItem.setText(items[i]);
                //editTextItem.setSelection(editTextItem.length());
                listPopupWindow.dismiss();
            }
        });
        // 点击imagebutton显示弹出菜单
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listPopupWindow.show();
            }
        });

        // 点击相应的checkbox也显示弹出菜单
        CheckBox checkBoxItem = (CheckBox) findViewById(R.id.checkBoxItem);
        checkBoxItem.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(compoundButton.isChecked()) listPopupWindow.show();
            }
        });

        // 初始化多选对话框
        EditText editTextRepeat = (EditText) findViewById(R.id.editTextRepeat);
        editTextRepeat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mutiDialog.show();
                //controlMutiDialog(true);
            }
        });
        mutiDialog = createMutiDialog(editTextRepeat);

        // checkboxrepeat
        final CheckBox checkBoxRepeat = (CheckBox) findViewById(R.id.checkBoxRepeat);
        checkBoxRepeat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (compoundButton.isChecked())  mutiDialog.show();
            }
        });

        // 设定button
        Button alarmBtn = (Button) findViewById(R.id.timeBtn);
        alarmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Integer taskId;
                if (getIntent().getBooleanExtra("reset", false)) {
                    taskId = getIntent().getIntExtra("taskId", -1);
                } else {
                    taskId = getValidTaskId();      // 获取有效的任务id
                }
                String weekday=" ";
                int h = timePicker.getCurrentHour();
                int m = timePicker.getCurrentMinute();

                Intent intentTemp = new Intent(HealthAlarmActivity.this, AlarmReceiver.class);
                intentTemp.putExtra("taskId", taskId);
                intentTemp.putExtra("tag", editTextItem.getText().toString());
                intentTemp.putExtra("vibration", checkBoxShock.isChecked());
                PendingIntent pendingIntent = PendingIntent.getBroadcast(HealthAlarmActivity.this, taskId, intentTemp, PendingIntent.FLAG_CANCEL_CURRENT);

                if (!checkBoxRepeat.isChecked()) {
                    calendar.set(Calendar.HOUR_OF_DAY, h);
                    calendar.set(Calendar.MINUTE, m);
                    //将秒和毫秒设置为0
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 0);
                    //建立Intent和PendingIntent来调用闹钟管理器

                    //获取闹钟管理器
                    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                } else {
                    weekday = "";
                    int count = 0;
                    for (int j = 0; j < 7; j++) {
                        if (checkeditems[j]) {
                            int temp = repeatAlarm(h,m,j+1,pendingIntent);
                            weekday = weekday + " " + Integer.toString(temp);
                        } else {
                            weekday = weekday + " 0";
                            count++;
                        }
                    }
                    if (7 == count) checkBoxRepeat.setChecked(false);
                }

                // 取出数据，回传，返回之前的activity
                Intent backIntent = new Intent(HealthAlarmActivity.this, HealthReminderActivity.class);
                String tag = editTextItem.getText().toString();
                if (0 != tag.length()) {
                    backIntent.putExtra("tag", tag);
                    backIntent.putExtra("vibration", checkBoxShock.isChecked());
                    backIntent.putExtra("taskId", taskId);
                    backIntent.putExtra("time", formatTime(h, m));
                    backIntent.putExtra("repeat", checkBoxRepeat.isChecked());
                    backIntent.putExtra("weekday", weekday.substring(1));
                    backIntent.putExtra("reset", false);

                    startActivity(backIntent);
                    SharedApplication.showToast(HealthAlarmActivity.this, "闹钟时间为:" + formatTime(h,m)
                            + " 标题:" + tag);
                }
            }
        });
    }

    // 创建多选对话框，选择day
    private AlertDialog createMutiDialog(final EditText editText) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("重复");
        // 创建多选项
        builder.setMultiChoiceItems(new String[]{"星期一","星期二","星期三","星期四","星期五","星期六","星期日"}, checkeditems,
                new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                        checkeditems[i] = b;
                    }
                });
        builder.setNeutralButton("全选",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        controlMutiDialog(false);    // 保持对话框显示
                        Button btn = mutiDialog.getButton(AlertDialog.BUTTON_NEUTRAL);
                        ListView listView = mutiDialog.getListView();
                        if (!isAllChecked) { // 已经全选
                            btn.setText("反选");
                            isAllChecked = true;
                        } else {
                            btn.setText("全选");
                            isAllChecked = false;
                        }

                        for (int j = 0; j < listView.getCount(); j++) {
                            listView.setItemChecked(j, isAllChecked);
                            checkeditems[j] = isAllChecked;
                        }

                    }
                });

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ListView listView = mutiDialog.getListView();
                StringBuilder strb = new StringBuilder();
                strb.append("");
                for(int j = 0; j < listView.getCount(); j++) {
                    if (listView.isItemChecked(j)) {
                        checkeditems[j] = true;
                        strb.append(" "+items[j]);
                    }
                    else checkeditems[j] = false;
                }


                editText.setText(strb.toString());
                controlMutiDialog(true);
            }
        });

        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        /*
                        // 恢复初始状态
                        isAllChecked = false;
                        ListView listView = mutiDialog.getListView();
                        for(int j = 0; j < listView.getCount(); j++) {
                            listView.setItemChecked(j, false);
                            checkeditems[j] = false;
                        }
                        editText.setText("");
                        */
                        controlMutiDialog(true);
                    }
                });

        mutiDialog = builder.create();

        return  mutiDialog;
    }

    // 控制对话框的打开与关闭
    private void controlMutiDialog(boolean close){
        try {
            // 与一般网上方法的区别的原因，为最终获得父类Dialog
            Field field = mutiDialog.getClass().getSuperclass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(mutiDialog, close);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 格式化时间
    private String formatTime(int h, int m) {
        String hour = h+"";
        String minute = m+"";
        if(hour.length() < 2) hour = "0" + hour;
        if(minute.length() < 2) minute = "0" + minute;
        String timestr = hour+":"+minute;
        return timestr;
    }

    // 设置重复的闹钟
    private int repeatAlarm(int h, int m, int week, PendingIntent pendingIntent) {
        calendar.set(Calendar.DAY_OF_WEEK, week);
        calendar.set(Calendar.HOUR_OF_DAY, h);
        calendar.set(Calendar.MINUTE,m);
        //将秒和毫秒设置为0
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        //建立Intent和PendingIntent来调用闹钟管理器

        //获取闹钟管理器
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        //设置闹钟
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 7*24*60*60*1000, pendingIntent);

        return 1;
    }

    // 生成一个有效的任务id
    private int getValidTaskId() {
        Set<Integer> tasks = HealthReminderActivity.TaskIDs;
        while (true) {
            if (tasks.contains(taskCount)) {    // 此id已经用过，则加一
                taskCount++;
            } else {                            // 没有使用过返回此数作为id
                return taskCount;
            }
        }
    }
}
